package com.yulongtian.oneProblemEveryDay.month202211.day20221105;

import java.util.Stack;

/**
 * https://leetcode.cn/problems/parsing-a-boolean-expression/
 * 根据解答自己写出
 *
 * @author yulongTian
 * @create 2022-11-05 15:46
 */
public class Test01 {
    public static void main(String[] args) {
        System.out.println(parseBoolExpr("&(|(f))"));
    }

    public static boolean parseBoolExpr(String expression) {

        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < expression.length(); i++) {
            if (expression.charAt(i) == ',') {
                continue;
            }

            if (expression.charAt(i) != ',' && expression.charAt(i) != ')') {
                stack.push(expression.charAt(i));
            }

            if (expression.charAt(i) == ')') {
                int t_num = 0;
                int f_num = 0;
                while (stack.peek() != '(') {
                    Character pop = stack.pop();
                    if (pop == 't') {
                        t_num++;
                        continue;
                    }
                    if (pop == 'f') {
                        f_num++;
                        continue;
                    }
                }
                stack.pop();//弹出  “(”
                Character temp_operation = stack.pop();//弹出  运算符
                if (temp_operation == '!') {
                    if (f_num == 1) {
                        stack.push('t');
                    } else {
                        stack.push('f');
                    }
                }
                if (temp_operation == '&') {
                    if (f_num == 0) {
                        stack.push('t');
                    } else {
                        stack.push('f');
                    }
                }

                if (temp_operation == '|') {
                    if (t_num > 0) {
                        stack.push('t');
                    } else {
                        stack.push('f');
                    }
                }

            }

        }

        return stack.pop() == 't';
    }


}
